#include<stdio.h>
#include<stdlib.h>

typedef struct PolyNode* Polynomial;

struct PolyNode {
	int coefficient;
	int expon;
	Polynomial next;
};

void Attach(int d, int e, Polynomial* p)  
{
	Polynomial temp = (Polynomial)malloc(sizeof(struct PolyNode));
	temp->coefficient = d;
	temp->expon = e;
	temp->next = NULL;
	(*p)->next = temp;
	(*p) = temp;
}

Polynomial ReadPoly()    
{
	Polynomial p, r, temp;
	int d, e, N;
	p = (Polynomial)malloc(sizeof(struct PolyNode));
	p->next = NULL;
	r = p;
	scanf("%d", &N);  
	while (N--)
	{
		scanf("%d %d", &d, &e);
		Attach(d, e, &r);
	}
	temp = p;           
	p = p->next;
	free(temp);
	return p;
}

Polynomial initPoly(Polynomial p1, Polynomial p2)
{
	Polynomial p, t, r;
	p = (Polynomial)malloc(sizeof(struct PolyNode));
	p->next = NULL;
	t = (Polynomial)malloc(sizeof(struct PolyNode));
	t = p2;
	r = p;
	while (t)
	{
		Attach((p1->coefficient) * (t->coefficient), p1->expon + t->expon, &r);
		t = t->next;
	}
	return p;       
}

Polynomial Mult(Polynomial p1, Polynomial p2)
{
	Polynomial p3 = initPoly(p1, p2);
	Polynomial t1, t2, r, temp;
	int d, e;
	t1 = p1->next;
	while (t1)
	{
		r = p3;
		t2 = p2;
		while (t2)
		{
			d = (t1->coefficient) * (t2->coefficient);
			e = (t1->expon) + (t2->expon);
			while ((rear->next) && (rear->next->expon > e))  
			{
				r = r->next;
			}
			if ((r->next) && (r->next->expon == e))   
			{
				if (r->next->coefficient + d)             
				{
					r->next->coefficient += d;
				}
				else                                         
				{
					temp = r->next;
					r->next = temp->next;
					free(temp);
				}
			}
			else                                             
			{
				temp = (Polynomial)malloc(sizeof(struct PolyNode));
				temp->coefficient = d;
				temp->expon = e;
				temp->next = r->next;
				r->next = temp;
			}
			t2 = t2->next;
		}
		t1 = t1->next;
	}
	temp = p3;
	p3 = p3->next;
	free(temp);
	return p3;
}

void PrintPoly(Polynomial p)   
{
	Polynomial Q;
	Q = p;
	if (!Q)
		printf("0\n");
	while (Q->next)
	{
		printf("%dx^%d + ", Q->coefficient, Qptr->expon);
		Q = Q->next;
	}
	printf("%dx^%d\n", Q->coefficient, Q->expon);
}

int main()
{
	Polynomial p1, p2, result;
	p1 = ReadPoly();
	p2 = ReadPoly();
	result = Mult(p1, p2);
	printf("多项式1为：\n");
	PrintPoly(p1);
	printf("多项式2为：\n");
	PrintPoly(p2);
	printf("两式相乘结果为：\n");
	PrintPoly(result);
	return 0;
}
